package com.tt1000.settlementplatform.view;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.constraint.ConstraintLayout;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.tt1000.settlementplatform.MainActivity;
import com.tt1000.settlementplatform.R;
import com.tt1000.settlementplatform.app.MyApplication;
import com.tt1000.settlementplatform.base.BaseFragment;
import com.tt1000.settlementplatform.bean.member.DaoSession;
import com.tt1000.settlementplatform.bean.member.StoreConfig;
import com.tt1000.settlementplatform.bean.member.TfUserInfo;
import com.tt1000.settlementplatform.bean.member.TfUserInfoDao;
import com.tt1000.settlementplatform.bean.result_info.RegMachineResultInfo;
import com.tt1000.settlementplatform.utils.MyConstant;
import com.tt1000.settlementplatform.utils.MyUtil;

import java.util.ArrayList;
import java.util.List;

import rx.Observer;

import static com.tt1000.settlementplatform.utils.MyConstant.TAG;

@SuppressLint("ValidFragment")
public class LoginFragment extends BaseFragment {

    private Context mContext;

    // TODO: 2020/1/10 注释
//    private RecyclerView rcKeyboard;

    public Button btnLogin;
    public Button btnActivate;
    private EditText etUser;
    private EditText etPassword;
    private EditText etMachineCode;
    private TextView txUserId;
    public TextView txExpireDate;

    public ConstraintLayout constraintLayout;

    private AlertDialog mLoginWarningDialog;

    private List<String> keyboradList;
    private StringBuilder loginStringBuilder;
    public LinearLayout linearLayout;
    public LoginFragment() {
        super();
    }

//    @SuppressLint("ValidFragment")
//    public LoginFragment(FragmentManager mainFragmentManager) {
//        super(mainFragmentManager);
//    }

    @Override
    protected int setContentView() {
        return R.layout.fragment_login;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView();
        initData();
        init();
//        fillData();
    }
    private void fillData(){
        etUser.setText("18512345678");
        etPassword.setText("666666");
    }
    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        // 初始化
        txUserId.setText("");
        mainActivity.pUserInfo = null;
        mLoginWarningDialog = new AlertDialog.Builder(mContext)
                .setTitle("提示")
                .setMessage("当前无网络连接")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
//                        login();
                    }
                })
//                .setNegativeButton("取消", null)
                .create();
    }

    private void initView() {
        String loginNo = MyConstant.gSharedPre.getString("loginNo", "");
        mContext = rootView.getContext();
        // TODO: 2020/1/10 注释
//        rcKeyboard = rootView.findViewById(R.id.recycler_keyboard);
        btnLogin = rootView.findViewById(R.id.btn_login);
        btnActivate = (Button) findViewById(R.id.btn_login_activate);
        etUser = (EditText) findViewById(R.id.et_login_user);
        if (!TextUtils.isEmpty(loginNo)){
            etUser.setText(loginNo);
        }
        etPassword = (EditText) findViewById(R.id.et_login_password);
        etMachineCode = (EditText) findViewById(R.id.et_login_machine_activate_code);
        txUserId = mainActivity.findViewById(R.id.tx_user_id);
        txExpireDate = (TextView) findViewById(R.id.tx_login_machine_expire);
        constraintLayout = (ConstraintLayout) findViewById(R.id.cl_machine_expire);

//        etUser.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                MyUtil.hideInputMethodManager(mContext, etUser);
//            }
//        });
//
//        etPassword.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                MyUtil.hideInputMethodManager(mContext, etPassword);
//            }
//        });

        etUser.setFocusable(true);
        etUser.requestFocus();

    }

    private void initData() {
        loginStringBuilder = new StringBuilder();
        keyboradList = new ArrayList<>();
        keyboradList.add("7");
        keyboradList.add("8");
        keyboradList.add("9");
        keyboradList.add("退格(<-)");
        keyboradList.add("4");
        keyboradList.add("5");
        keyboradList.add("6");
        keyboradList.add("清除(c)");
        keyboradList.add("1");
        keyboradList.add("2");
        keyboradList.add("3");
        keyboradList.add(":");
        keyboradList.add("0");
        keyboradList.add(".");
        keyboradList.add("-");
        keyboradList.add(" ");
    }

    private void init() {

        btnActivate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final String machineNo = etMachineCode.getText().toString();
                if (!machineNo.isEmpty()) {
                    registerMachine(machineNo, new Observer<RegMachineResultInfo>() {
                        @Override
                        public void onCompleted() {

                        }

                        @Override
                        public void onError(Throwable e) {
                            Log.d(TAG, "onError: " + e.getMessage());
                            showMessage("提示", "绑定失败，请检查网络或地址(" + e.getMessage() +")");
                        }

                        @Override
                        public void onNext(final RegMachineResultInfo regMachineResultInfo) {
                            if (regMachineResultInfo.isResult()) {
                                String clientCode = regMachineResultInfo.getMachineInformation().get(0).getCLIENT_CODE();
                                String storeCode = regMachineResultInfo.getMachineInformation().get(0).getSTORE_CODE();
                                String machineName = regMachineResultInfo.getMachineInformation().get(0).getMACHINE_NAME();
                                String storeName = regMachineResultInfo.getStoreInformation().get(0).getSTORE_NAME();
                                String storeAddr = regMachineResultInfo.getStoreInformation().get(0).getSTORE_ADDR();
                                long machineExpire = regMachineResultInfo.getStoreInformation().get(0).getVAILD_TIME();
                                MyConstant.gEditor.putString(MyConstant.CLIENT_CODE, clientCode);
                                MyConstant.gEditor.putString(MyConstant.STORE_CODE, storeCode);
                                MyConstant.gEditor.putString(MyConstant.SP_MACHINE_NAME, machineName);
                                MyConstant.gEditor.putString(MyConstant.SP_STORE_NAME, storeName);
                                MyConstant.gEditor.putString(MyConstant.SP_STORE_ADDR, storeAddr);
                                MyConstant.gEditor.putBoolean(MyConstant.SP_REGISTER_MACHINE, true);
                                MyConstant.gEditor.putLong(MyConstant.SP_MACHINE_EXPIRE, machineExpire);
                                Log.d(TAG, "onNext: machineExpire ==> " + machineExpire);
                                Log.d(TAG, "onNext: SP_MACHINE_EXPIRE ==> " + MyConstant.gSharedPre.getLong(MyConstant.SP_MACHINE_EXPIRE, 0));
                                MyConstant.gEditor.putString(MyConstant.SP_MACHINE_NO, machineNo);
                                MyConstant.gEditor.commit();
                                RegMachineResultInfo.MachineInformationBean verifyMachineResultInfo =  regMachineResultInfo.getMachineInformation().get(0);
                                if (verifyMachineResultInfo.getUSE_STATUS().equals("0") && System.currentTimeMillis() < verifyMachineResultInfo.getVAILD_TIME()) {
                                    mainActivity.runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            try {
                                                constraintLayout.setVisibility(View.GONE);
                                                btnLogin.setEnabled(true);
                                                txExpireDate.setText(MyUtil.dateConversion(regMachineResultInfo.getMachineInformation().get(0).getVAILD_TIME()));
                                            } catch (Exception e) {
                                                e.printStackTrace();
                                            }
                                        }
                                    });
                                } else {
                                    showMessage("提示", "激活码无效！");
                                }
                            }
                            showMessage("提示", regMachineResultInfo.getMsg());
                        }
                    });
                } else {
                    showMessage("提示", "请输入激活码！");
                }
            }
        });

        btnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String loginNo = etUser.getText().toString();
                String password = etPassword.getText().toString();
                if (loginNo.isEmpty() || password.isEmpty()) {
                    showMessage("提示", "请输入完整的登陆信息");
                    return;
                }
                if (mainActivity.machineExpire) {
                    showMessage("", "当前机器已到期！请续费后在做尝试");
                    return;
                }
                // 餐次营业
//                Date startTime = null, endTime = null, curTime = null;
//                List<TfMealTimes> tfMealTimesList = pDaoSession.queryBuilder(TfMealTimes.class)
//                        .build()
//                        .list();
//                SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
//                boolean operation = false;
//                try {
//                    for (TfMealTimes mealTimes : tfMealTimesList) {
//                        startTime = format.parse(mealTimes.getSTARTTIME());
//                        endTime = format.parse(mealTimes.getENDTIME());
//                        curTime = format.parse(MyUtil.obtainCurrentSysDate(1));
//                        if (curTime.getTime() >= startTime.getTime() && curTime.getTime() <= endTime.getTime()) {
//                            operation = true;
//                            break;
//                        }
//                    }
//                    if (!operation) {
//                        StringBuilder sb = new StringBuilder();
//                        for (TfMealTimes mealTimes : tfMealTimesList) {
//                            sb.append(mealTimes.getMT_NAME() + " : " + mealTimes.getSTARTTIME() + " ~ " + mealTimes.getENDTIME() + "\n");
//                        }
//                        if (!sb.toString().trim().isEmpty()) {
//                            showMessage("营业时间：", sb.toString());
//                        } else {
//                            showMessage("警告", "数据同步不完整");
//                        }
//                        return;
//                    }
//
//                } catch (ParseException e) {
//                    e.printStackTrace();
//                }

                if (judegeLoginUser(loginNo, password)) {
                    MyConstant.gEditor.putString("loginNo",loginNo);
                    MyConstant.gEditor.commit();
//                    if (!MyUtil.networkState || !mainActivity.wifiState || !MyUtil.isConfigServer()) {
                    if (!MyUtil.obtainNetworkStatus(getActivity())) {
                        // 离线登陆，风险提示（offline login，risk warning）
                        mLoginWarningDialog.show();
                    } else {
                        login();
                    }
                } else {
                    showMessage("提示", "账户或密码错误");
                }
//                HomeFragment homeFragment = new HomeFragment(mainFragmentManager);
//                MainActivity.gUiHandler.obtainMessage(MyConstant.REPLACE_FRAGMENT_TO_STACK,  homeFragment).sendToTarget();
//                appTitle.setText("主界面");
//                txUserId.setText(etUser.getText().toString());
            }
        });

        // 动态设置输入框和按钮宽高
        linearLayout = (LinearLayout) findViewById(R.id.ll_login);
        linearLayout.post(new Runnable() {
            @Override
            public void run() {
                int width = (int) (linearLayout.getWidth() / 3.5);
                int height = width / 4 ;
                etUser.setWidth(width);
                etUser.setHeight(height);
                etPassword.setWidth(width);
                etPassword.setHeight(height);
                etPassword.setWidth(width);
                etPassword.setHeight(height);
                // TODO: 2020/1/10 注释
//                MyAdapter adapter = new MyAdapter(width);
//                adapter.setListener(new LoginClickListener() {
//                    @Override
//                    public void onClick(int position) {
//                        inputFromKeyboard(position);
//                    }
//                });
//
//                rcKeyboard.setLayoutManager(new GridLayoutManager(mContext, 4));
//                rcKeyboard.setAdapter(adapter);
            }
        });
    }
    //调用隐藏系统默认的输入法
    public static void showOrHide(Context context, Activity activity) {
        ((InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE))
                .hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(),
                        InputMethodManager.HIDE_NOT_ALWAYS);
    }
    public void login() {
        BaseFragment fragment = new HomeFragment();
        String title = "";
        switch (mainActivity.pUserInfo.getUTYPE()) {
            case "1":
                // operator
                title = getString(R.string.operate);
                fragment = new BusSettlementFragment();
                break;
            case "2":
            case "3":
                // admin
                title = getString(R.string.home);
                fragment = new HomeFragment();
                showOrHide(mContext,mainActivity);
                break;
                default:
                    Toast.makeText(mContext, "身份有误", Toast.LENGTH_SHORT).show();
                    return;

        }
        MainActivity.gUiHandler.obtainMessage(MyConstant.REPLACE_FRAGMENT_TO_STACK,  fragment).sendToTarget();
        //开启定时任务
        MainActivity.gUiHandler.sendEmptyMessage(MainActivity.START_SCHEDULE_TASK);
        appTitle.setText(title);
        txUserId.setText(etUser.getText().toString());
        // 清除登陆数据
        etUser.setText("");
        etPassword.setText("");
    }

    public boolean judegeLoginUser(String loginNo, String passwrod) {
        // password need to be encrypt before they are added to the database
        String encryptPwd = MyUtil.encryptMD5(passwrod);
        DaoSession session = MyApplication.getInstance();
        List<TfUserInfo> infoList = session.queryBuilder(TfUserInfo.class)
                .where(TfUserInfoDao.Properties.ULOGINNO.eq(loginNo),
                        TfUserInfoDao.Properties.UPASSWORD.eq(encryptPwd))
                .build()
                .list();
        TfUserInfo info;
        if (infoList.isEmpty()) {
            info = null;
        } else {
            info = infoList.get(0);
        }
        if (info != null) {
            // 记录
            mainActivity.pUserInfo = info;
            List<StoreConfig> storeConfigList = session.queryBuilder(StoreConfig.class)
                    .build()
                    .list();
            if (!storeConfigList.isEmpty() && storeConfigList != null) {
                mainActivity.pStoreConfig = storeConfigList.get(0);
            }
            return true;
        } else {
            return false;
        }
    }

    public void inputFromKeyboard(int position) {
        EditText receiveEdit = null;
        if (etUser.isFocused()) {
            receiveEdit = etUser;
        } else if (etPassword.isFocused()) {
            receiveEdit = etPassword;
        }
        if (receiveEdit == null) {
            return;
        }
        switch (position) {
            case 0 :
                addToEdit(receiveEdit, "7");
                break;
            case 1 :
                addToEdit(receiveEdit, "8");
                break;
            case 2 :
                addToEdit(receiveEdit, "9");
                break;
            case 3 :
                // 退格
                int index = receiveEdit.getSelectionStart();
                int lenght = receiveEdit.getText().length();
                if (lenght > 0){
                    String oldContent;
                    String newContent;
                    if (index == lenght) {
                        oldContent = "";
                        newContent = receiveEdit.getText().toString().substring(0, index - 1);
                    } else {
                        oldContent = receiveEdit.getText().toString().substring(index, lenght);
                        newContent = receiveEdit.getText().toString().substring(0, index == 0 ? 0 : index - 1);
                    }
                    receiveEdit.setText(newContent + oldContent);
                    receiveEdit.setSelection(index == 0 ? 0 : index - 1);
                }
                break;
            case 4 :
                addToEdit(receiveEdit, "4");
                break;
            case 5 :
                addToEdit(receiveEdit, "5");
                break;
            case 6 :
                addToEdit(receiveEdit, "6");
                break;
            case 7 :
                // C 清除
                receiveEdit.setText("");
                break;
            case 8 :
                addToEdit(receiveEdit, "1");
                break;
            case 9 :
                addToEdit(receiveEdit, "2");
                break;
            case 10 :
                addToEdit(receiveEdit, "3");
                break;
            case 11 :
                addToEdit(receiveEdit, ":");
                break;
            case 12 :
                addToEdit(receiveEdit, "0");
                break;
            case 13 :
                addToEdit(receiveEdit, ".");
                break;
            case 14 :
                addToEdit(receiveEdit, "-");
                break;
            case 15 :
                addToEdit(receiveEdit, " ");
                break;
            default:
                break;
        }
    }

    public void addToEdit(EditText editText, String newContent) {
        try {
            String upStr = "", footStr = "";
            int index = editText.getSelectionStart();
            String content = editText.getText().toString();
            upStr = content.substring(0, index);
            footStr = content.substring(index);
            editText.setText(upStr + newContent + footStr);
            editText.setSelection(index+ newContent.length());
        } catch (Exception e) {

        }
    }

    class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {

        public LoginClickListener loginClickListener;
        int width;
        public MyAdapter(int width) {
            this.width = width;
        }

        public void setListener(LoginClickListener listener) {
            loginClickListener = listener;
        }

        @Override
        public MyAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.gridview_login_item, parent, false);
            return  new ViewHolder(view);
        }

        @Override
        public void onBindViewHolder(MyAdapter.ViewHolder holder, final int position) {
            holder.button.setWidth(width / 2);
            holder.button.setHeight(width / 3);
            holder.button.setText(keyboradList.get(position));
            if (position == 3 || position == 7) {
                holder.button.setTextSize(12);
            }
            holder.button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    // 隐藏输入法
                    if (etPassword.isFocused()) {
                        MyUtil.hideInputMethodManager(mContext, etPassword);
                    } else if (etUser.isFocused()){
                        MyUtil.hideInputMethodManager(mContext, etUser);
                    }

                    if (loginClickListener != null) {
                        loginClickListener.onClick(position);
                    }

                }
            });
        }

        @Override
        public int getItemCount() {
            return keyboradList.size();
        }

        public class ViewHolder extends RecyclerView.ViewHolder {
            Button button;
            public ViewHolder(View itemView) {
                super(itemView);
                button = itemView.findViewById(R.id.btn_statistics_item);
            }
        }
    }

    public interface LoginClickListener {
        void onClick(int position);
    }

    @Override
    public void onStop() {
        super.onStop();
        if (rootView != null) {
            rootView = null;
        }
        Log.d(TAG, "onStop: ");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "onDestroy: ");
    }
}
